import React, { useState, useEffect } from 'react';
import { Table, Button, Space, Modal, Form, Input, message, Tabs, Tag, Select, DatePicker, InputNumber } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { PromotionApi, CouponTemplateVO, SeckillActivityVO, BargainActivityVO } from '../../../api/mall/promotion';
import dayjs from 'dayjs';

const { TabPane } = Tabs;
const { Option } = Select;
const { TextArea } = Input;
const { RangePicker } = DatePicker;

const MallPromotion: React.FC = () => {
  const [coupons, setCoupons] = useState<CouponTemplateVO[]>([]);
  const [seckills, setSeckills] = useState<SeckillActivityVO[]>([]);
  const [bargains, setBargains] = useState<BargainActivityVO[]>([]);
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState('coupon');
  const [modalVisible, setModalVisible] = useState(false);
  const [editingItem, setEditingItem] = useState<any>(null);
  const [form] = Form.useForm();

  // 获取优惠券列表
  const fetchCoupons = async () => {
    setLoading(true);
    try {
      const response = await PromotionApi.getCouponTemplatePage({});
      setCoupons(response.data?.list || []);
    } catch (error) {
      message.error('获取优惠券列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取秒杀活动列表
  const fetchSeckills = async () => {
    setLoading(true);
    try {
      const response = await PromotionApi.getSeckillActivityPage({});
      setSeckills(response.data?.list || []);
    } catch (error) {
      message.error('获取秒杀活动列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取砍价活动列表
  const fetchBargains = async () => {
    setLoading(true);
    try {
      const response = await PromotionApi.getBargainActivityPage({});
      setBargains(response.data?.list || []);
    } catch (error) {
      message.error('获取砍价活动列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (activeTab === 'coupon') {
      fetchCoupons();
    } else if (activeTab === 'seckill') {
      fetchSeckills();
    } else if (activeTab === 'bargain') {
      fetchBargains();
    }
  }, [activeTab]);

  // 保存数据
  const handleSave = async (values: any) => {
    try {
      let apiCall;
      const data = { ...values };

      // 处理时间范围
      if (values.timeRange) {
        data.startTime = values.timeRange[0].format('YYYY-MM-DD HH:mm:ss');
        data.endTime = values.timeRange[1].format('YYYY-MM-DD HH:mm:ss');
        delete data.timeRange;
      }

      if (activeTab === 'coupon') {
        apiCall = editingItem 
          ? PromotionApi.updateCouponTemplate({ ...editingItem, ...data })
          : PromotionApi.createCouponTemplate(data);
      } else if (activeTab === 'seckill') {
        apiCall = editingItem 
          ? PromotionApi.updateSeckillActivity({ ...editingItem, ...data })
          : PromotionApi.createSeckillActivity(data);
      } else if (activeTab === 'bargain') {
        apiCall = editingItem 
          ? PromotionApi.updateBargainActivity({ ...editingItem, ...data })
          : PromotionApi.createBargainActivity(data);
      }

      await apiCall;
      message.success(editingItem ? '更新成功' : '创建成功');
      setModalVisible(false);
      setEditingItem(null);
      form.resetFields();
      
      // 刷新对应列表
      if (activeTab === 'coupon') fetchCoupons();
      else if (activeTab === 'seckill') fetchSeckills();
      else if (activeTab === 'bargain') fetchBargains();
    } catch (error) {
      message.error(editingItem ? '更新失败' : '创建失败');
    }
  };

  // 删除数据
  const handleDelete = async (id: number) => {
    try {
      if (activeTab === 'coupon') {
        await PromotionApi.deleteCouponTemplate(id);
      } else if (activeTab === 'seckill') {
        await PromotionApi.deleteSeckillActivity(id);
      } else if (activeTab === 'bargain') {
        await PromotionApi.deleteBargainActivity(id);
      }
      
      message.success('删除成功');
      
      // 刷新对应列表
      if (activeTab === 'coupon') fetchCoupons();
      else if (activeTab === 'seckill') fetchSeckills();
      else if (activeTab === 'bargain') fetchBargains();
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 打开编辑模态框
  const openEditModal = (item: any) => {
    setEditingItem(item);
    const formData = { ...item };
    
    // 处理时间范围
    if (item.startTime && item.endTime) {
      formData.timeRange = [dayjs(item.startTime), dayjs(item.endTime)];
    }
    
    form.setFieldsValue(formData);
    setModalVisible(true);
  };

  // 打开新增模态框
  const openAddModal = () => {
    setEditingItem(null);
    form.resetFields();
    setModalVisible(true);
  };

  const getStatusTag = (status: number) => {
    const statusMap: Record<number, { color: string; text: string }> = {
      0: { color: 'orange', text: '未开始' },
      1: { color: 'green', text: '进行中' },
      2: { color: 'red', text: '已结束' },
      3: { color: 'gray', text: '已关闭' }
    };
    const statusInfo = statusMap[status] || { color: 'default', text: '未知' };
    return <Tag color={statusInfo.color}>{statusInfo.text}</Tag>;
  };

  // 优惠券列表列
  const couponColumns = [
    {
      title: '优惠券名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '优惠类型',
      dataIndex: 'discountType',
      key: 'discountType',
      render: (type: number) => type === 1 ? '满减' : '打折',
    },
    {
      title: '优惠金额/折扣',
      key: 'discount',
      render: (_: any, record: CouponTemplateVO) => {
        return record.discountType === 1 
          ? `¥${(record.discountPrice! / 100).toFixed(2)}`
          : `${record.discountPercent}折`;
      },
    },
    {
      title: '使用门槛',
      dataIndex: 'usePrice',
      key: 'usePrice',
      render: (price: number) => price > 0 ? `满¥${(price / 100).toFixed(2)}` : '无门槛',
    },
    {
      title: '发放数量',
      dataIndex: 'totalCount',
      key: 'totalCount',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: number) => getStatusTag(status),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: CouponTemplateVO) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => openEditModal(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id!)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  // 秒杀活动列表列
  const seckillColumns = [
    {
      title: '活动名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
      key: 'startTime',
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      key: 'endTime',
    },
    {
      title: '排序',
      dataIndex: 'sort',
      key: 'sort',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: number) => getStatusTag(status),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: SeckillActivityVO) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => openEditModal(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id!)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  // 砍价活动列表列
  const bargainColumns = [
    {
      title: '活动名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
      key: 'startTime',
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      key: 'endTime',
    },
    {
      title: '参与人数',
      dataIndex: 'userSize',
      key: 'userSize',
    },
    {
      title: '砍价次数',
      dataIndex: 'bargainCount',
      key: 'bargainCount',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: number) => getStatusTag(status),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: BargainActivityVO) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => openEditModal(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id!)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const getCurrentData = (): any[] => {
    switch (activeTab) {
      case 'coupon':
        return coupons;
      case 'seckill':
        return seckills;
      case 'bargain':
        return bargains;
      default:
        return [];
    }
  };

  const getCurrentColumns = (): any[] => {
    switch (activeTab) {
      case 'coupon':
        return couponColumns;
      case 'seckill':
        return seckillColumns;
      case 'bargain':
        return bargainColumns;
      default:
        return couponColumns;
    }
  };

  const renderFormItems = () => {
    if (activeTab === 'coupon') {
      return (
        <>
          <Form.Item
            name="name"
            label="优惠券名称"
            rules={[{ required: true, message: '请输入优惠券名称' }]}
          >
            <Input placeholder="请输入优惠券名称" />
          </Form.Item>
          <Form.Item
            name="discountType"
            label="优惠类型"
            rules={[{ required: true, message: '请选择优惠类型' }]}
          >
            <Select placeholder="请选择优惠类型">
              <Option value={1}>满减</Option>
              <Option value={2}>打折</Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="discountPrice"
            label="优惠金额（分）"
          >
            <InputNumber placeholder="请输入优惠金额" style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item
            name="discountPercent"
            label="折扣百分比"
          >
            <InputNumber placeholder="请输入折扣百分比" style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item
            name="usePrice"
            label="使用门槛（分）"
          >
            <InputNumber placeholder="请输入使用门槛" style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item
            name="totalCount"
            label="发放数量"
            rules={[{ required: true, message: '请输入发放数量' }]}
          >
            <InputNumber placeholder="请输入发放数量" style={{ width: '100%' }} />
          </Form.Item>
        </>
      );
    } else if (activeTab === 'seckill') {
      return (
        <>
          <Form.Item
            name="name"
            label="活动名称"
            rules={[{ required: true, message: '请输入活动名称' }]}
          >
            <Input placeholder="请输入活动名称" />
          </Form.Item>
          <Form.Item
            name="timeRange"
            label="活动时间"
            rules={[{ required: true, message: '请选择活动时间' }]}
          >
            <RangePicker
              showTime
              format="YYYY-MM-DD HH:mm:ss"
              style={{ width: '100%' }}
            />
          </Form.Item>
          <Form.Item
            name="sort"
            label="排序"
          >
            <InputNumber placeholder="请输入排序" style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item
            name="remark"
            label="备注"
          >
            <TextArea placeholder="请输入备注" rows={3} />
          </Form.Item>
        </>
      );
    } else if (activeTab === 'bargain') {
      return (
        <>
          <Form.Item
            name="name"
            label="活动名称"
            rules={[{ required: true, message: '请输入活动名称' }]}
          >
            <Input placeholder="请输入活动名称" />
          </Form.Item>
          <Form.Item
            name="timeRange"
            label="活动时间"
            rules={[{ required: true, message: '请选择活动时间' }]}
          >
            <RangePicker
              showTime
              format="YYYY-MM-DD HH:mm:ss"
              style={{ width: '100%' }}
            />
          </Form.Item>
          <Form.Item
            name="userSize"
            label="参与人数"
            rules={[{ required: true, message: '请输入参与人数' }]}
          >
            <InputNumber placeholder="请输入参与人数" style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item
            name="bargainCount"
            label="砍价次数"
            rules={[{ required: true, message: '请输入砍价次数' }]}
          >
            <InputNumber placeholder="请输入砍价次数" style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item
            name="spuId"
            label="商品ID"
            rules={[{ required: true, message: '请输入商品ID' }]}
          >
            <InputNumber placeholder="请输入商品ID" style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item
            name="skuId"
            label="SKU ID"
            rules={[{ required: true, message: '请输入SKU ID' }]}
          >
            <InputNumber placeholder="请输入SKU ID" style={{ width: '100%' }} />
          </Form.Item>
        </>
      );
    }
    return null;
  };

  return (
    <div style={{ padding: '24px' }}>
      <div style={{ marginBottom: '16px' }}>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={openAddModal}
        >
          新增{activeTab === 'coupon' ? '优惠券' : activeTab === 'seckill' ? '秒杀活动' : '砍价活动'}
        </Button>
      </div>

      <Tabs activeKey={activeTab} onChange={setActiveTab}>
        <TabPane tab="优惠券管理" key="coupon" />
        <TabPane tab="秒杀活动" key="seckill" />
        <TabPane tab="砍价活动" key="bargain" />
      </Tabs>

      <Table
        columns={getCurrentColumns()}
        dataSource={getCurrentData()}
        rowKey="id"
        loading={loading}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条记录`,
        }}
      />

      <Modal
        title={`${editingItem ? '编辑' : '新增'}${activeTab === 'coupon' ? '优惠券' : activeTab === 'seckill' ? '秒杀活动' : '砍价活动'}`}
        open={modalVisible}
        onCancel={() => {
          setModalVisible(false);
          setEditingItem(null);
          form.resetFields();
        }}
        onOk={() => form.submit()}
        destroyOnClose
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSave}
        >
          {renderFormItems()}
        </Form>
      </Modal>
    </div>
  );
};

export default MallPromotion;